package com.aps.apspda.base;

import android.app.Application;
import android.content.Context;
import android.util.DisplayMetrics;

import com.aps.apspda.utils.AppUtils;
import com.aps.apspda.utils.StaticMembers;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import okhttp3.OkHttpClient;


/**
 * @author jaxhuang
 * @date 2017/9/15
 * @desc
 */

public class App extends Application {
    public static Context appContext;
    private static OkGo okGo;

    @Override
    public void onCreate() {
        super.onCreate();
        appContext = getApplicationContext();
        init();
        initOkGo();
        CrashHandler.getInstance().init(this);
    }

    private void init() {

        DisplayMetrics metrics = getResources().getDisplayMetrics();
        StaticMembers.STATUS_HEIGHT = AppUtils.getStatusHeight(this);
        StaticMembers.SCREEN_WIDTH = metrics.widthPixels;
        StaticMembers.SCREEN_HEIGHT = metrics.heightPixels;
        if (AppUtils.isEn()) {
            StaticMembers.Lan = "en";
        }

        String ip = AppUtils.getSharePre("URL_FILE", "URL_IP");
        if (ip.length() > 0) {
            StaticMembers.NET_URL = ip;
        } else {
            AppUtils.setSharePre("URL_FILE", "URL_IP", StaticMembers.NET_URL);
        }

        String fileIP = AppUtils.getSharePre("URL_FILE", "FILE_IP");
        if (fileIP.length() > 0) {
            StaticMembers.PIC_URL = fileIP;
        } else {
            AppUtils.setSharePre("URL_FILE", "FILE_IP", StaticMembers.PIC_URL);
        }
    }


    private void initOkGo() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //log相关
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);        //log打印级别，决定了log显示的详细程度
        loggingInterceptor.setColorLevel(Level.INFO);                               //log颜色级别，决定了log在控制台显示的颜色
        builder.addInterceptor(loggingInterceptor);                                 //添加OkGo默认debug日志
        builder.connectTimeout(StaticMembers.CONNECT_OUT_TIME, TimeUnit.MILLISECONDS); //请求超时时间
        builder.readTimeout(StaticMembers.CONNECT_OUT_TIME, TimeUnit.MILLISECONDS);
        builder.writeTimeout(StaticMembers.CONNECT_OUT_TIME, TimeUnit.MILLISECONDS);

        okGo = OkGo.getInstance().init(this);                           //必须调用初始化
        okGo.setOkHttpClient(builder.build())               //建议设置OkHttpClient，不设置会使用默认的
                .setCacheMode(CacheMode.NO_CACHE)               //全局统一缓存模式，默认不使用缓存，可以不传
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)   //全局统一缓存时间，默认永不过期，可以不传
                .setRetryCount(0);                   //全局统一超时重连次数，默认为三次，那么最差的情况会请求4次(一次原始请求，三次重连请求)，不需要可以设置为0
    }
}
